package com.smartguard.util;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtil {
	private static XMLUtil xmlUtil = XMLUtil.getXMLUtil(MailUtil.class.getClassLoader().getResourceAsStream("mail.xml"));
	private static String myEmail = xmlUtil.getParam("email");
	private static String password = xmlUtil.getParam("password");
	public static boolean sendEmail(String username, String toEmail){
		Properties properties = System.getProperties();
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.host", "smtp.163.com");

		Session session = Session.getInstance(properties, new Authenticator(){
			@Override
			public PasswordAuthentication getPasswordAuthentication(){
				return new PasswordAuthentication(myEmail, password);
			}
		});
		
		MimeMessage message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(myEmail));
			message.setRecipient(RecipientType.TO, new InternetAddress(toEmail));
			message.setSubject("Message from SmartGuard");
			//content = new String(content.getBytes("GBK"), "utf-8");
			String new_content = "<p>尊敬的"+username+"，您设置的监控区域内出现异常状况！</p><p>请勿回复此邮件。</p>";
			message.setContent(new_content, "text/html;charset=utf-8");
			Transport.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	
	public static void main(String[] args) {
		sendEmail("哈哈", "935805490@qq.com");
	}

}
